import React, { useEffect, useState } from 'react'
import { InboxOutlined } from '@ant-design/icons'
import { message, Typography, Upload } from 'antd'
import './index.less'
import { downloadByOwnUrl } from '@/utils/util'
const { Dragger } = Upload
interface IProps {
  max?: number
  value?: string
  onChange?: (...set: any) => void
  multiple?: boolean
  templateUrl?: string
  templateText?: string
  isModal?: boolean
}
const UploadFile = (props: IProps) => {
  const [fileList, setFileList] = useState<any[]>([])
  useEffect(() => {
    if (props.value && typeof props.value === 'string') {
      setFileList(props.value.split(',')?.map((item: string) => ({ url: item, name: item })))
    }
  }, [props.value])

  const handleChange = (info: any) => {
    const { fileList: newFileList } = info
    setFileList(newFileList)
    if (info?.file?.response?.code === 402) {
      message.error(info?.file?.response?.message)
      setTimeout(() => {
        setFileList(newFileList.slice(0, newFileList.length - 1))
      }, 500)
    } else {
      if (info.file.status === 'done') {
        setFileList(newFileList)
        const url = newFileList?.map((item: any) => item?.response?.data?.linkUrl || item?.url).join(',')
        props.onChange && props.onChange(url)
      }
    }
  }

  const handleOnRemove = (file: any) => {
    const newFileList = fileList?.filter((item: any) => item.uid !== file.uid)
    setFileList(newFileList)
    const url = newFileList.map((item: any) => item?.response?.data || item?.url).join(',')
    props.onChange && props.onChange(url)
  }
  const download = (url: string) => {
    downloadByOwnUrl(url)
  }
  return (
    <>
      <Dragger
        action={`/api/sop/sop/file/upload`}
        multiple={props.multiple ? props.multiple : false}
        name="file"
        onChange={handleChange}
        onRemove={handleOnRemove}
        fileList={fileList}
        maxCount={props?.max || 3}
      >
        <div
          className="custom_fileupload_wrap"
          style={{ padding: props.isModal ? 0 : '', minWidth: props.isModal ? 'auto' : '' }}
        >
          <p className="ant_upload_drag_icon">
            <InboxOutlined className="ant_upload_drag_icon_item" />
          </p>
          <p className="ant_upload_text">点击或拖动文件到此区域进行上传</p>
          <p className="ant_upload_hint">支持单次或批量上传</p>
        </div>
      </Dragger>
      {props?.templateUrl ? (
        <div className="uploadfile_template_text">
          <Typography.Link
            onClick={() => {
              download(props.templateUrl!)
            }}
          >
            {props.templateText ? props.templateText : '点击下载模板'}
          </Typography.Link>
        </div>
      ) : null}
    </>
  )
}
export default UploadFile
